package com.dy.agent.agent.api.web.controller.utils;

import java.util.regex.Pattern;

import org.slf4j.Logger;

import com.dy.agent.agent.api.exception.CommonException;
import com.dy.agent.agent.api.web.controller.vo.ResultWrapper;

/**
 * Created by luohao on 2016/11/30.
 */
public final class ResultUtils {

	private ResultUtils() {
	}

	public static ResultWrapper<?> as(Object result, int code, String message) {
		ResultWrapper resultVO = new ResultWrapper<Object>();
		resultVO.setCode(code);
		resultVO.setResult(result);
		resultVO.setErrorMsg(message);
		return resultVO;
	}

	public static ResultWrapper asSuccess(Object result) {
		return as(result, 0, "操作成功");
	}

	public static ResultWrapper asSuccess() {
		return as(null, 0, "操作成功");
	}

	public static ResultWrapper asError(String message) {
		return asError(null, message);
	}

	public static ResultWrapper asError(String message, Logger logger, Exception e) {
		logger.error("出现未知异常：" + message, e);
		return asError(null, message + "【" + e.getMessage() + "】");
	}

	public static ResultWrapper asError(String message, Exception e) {

		return asError(null, message + "【" + e.getMessage() + "】");
	}

	public static ResultWrapper asError(CommonException exception) {
		// logger.error("出现未知异常：" + message, e);
		return as(null, exception.getErrorCode().getCode(),
				exception.getMessage() != null ? exception.getMessage() : exception.getErrorCode().getMsg());
	}

	public static boolean isMatch(Pattern pattern, String testString) {
		return pattern.matcher(testString).find();
	}

	public static ResultWrapper asError(Object result, String message) {
		return as(result, 1, message);
	}

}
